_G.commonlib = _G.commonlib or {};

-- 挂载CAPI到commonlib上
for key, value in pairs(_G.__application__ or {}) do
    if (type(key) == "string" and string.match(key, "^%u[%u%l]*")) then
        if (type(value) == "function") then
            commonlib[key] = value;
        elseif (type(value) == "table") then
            commonlib[key] = value;
        -- else
        --     print(key, type(value));
        end
    -- else
    --     print(key, type(value));
    end
end

-- 加载原生lua脚本文件
local function load_asset_script(filename)
    local script_filename = commonlib.FormatPath(commonlib.GetScriptDirectory() .. "/" .. filename);
    local lua_text = commonlib.GetScriptTextByFilePath(script_filename);
    --commonlib.LOG_INFO("script_filename:" .. script_filename);
    --commonlib.LOG_INFO("script_text:" .. lua_text);
    _G.xpcall(function()
        if (lua_text == "") then
            commonlib.LOG_INFO("file: " .. script_filename .. " is empty!!!");
        end
        local func, errmsg = _G.load(lua_text, script_filename, "bt");
        if (not func) then
            commonlib.LOG_ERROR(errmsg);
            commonlib.LOG_ERROR("load: " .. script_filename .. " failed");
        else
            func();
        end
    end, function(errmsg)
        commonlib.LOG_ERROR(errmsg);
        debug.traceback();
    end);
end

commonlib.LOG_INFO("=========================lua application begin============================");

-- 加载commonlib
load_asset_script("lua_extension/init.lua");
load_asset_script("commonlib/init.lua");

-- commonlib.import(commonlib.__script_directory__ .. "/BlockEngine/init.lua");
-- commonlib.import(commonlib.__script_directory__ .. "/window/init.lua");
-- commonlib.import(commonlib.__script_directory__ .. "/blockly/init.lua");
-- commonlib.import(commonlib.__script_directory__ .. "/ui/init.lua");
-- commonlib.import(commonlib.__script_directory__ .. "/webserver/init.lua");
-- commonlib.import(commonlib.__script_directory__ .. "/app/init.lua");

commonlib.LOG_INFO("=========================lua application end============================");



-- local websocket = commonlib.LuaSocket("websocket");

-- websocket:Connect("127.0.0.1", 9000)

-- websocket:OnConnect(function()
--     websocket:Send("hello world")
-- end);

-- websocket:OnReceive(function(msg)
--     commonlib.LOG_INFO(msg);
-- end)